import uuid
from fastapi import APIRouter, Depends, HTTPException, status,Request
import requests
import json
import time
import base64
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.serialization import load_pem_private_key
from cryptography.hazmat.primitives.asymmetric.padding import PKCS1v15
from ... import settings
from .import sheams
from ...utils.const import Method

app = APIRouter()

# 加载私钥
with open(settings.WECHAT['privater_key_path'], "rb") as f:
    private_key = load_pem_private_key(f.read(), password=None)

def generate_signature(message):
    """生成签名"""
    signature = private_key.sign( data=message.encode(),
        padding=PKCS1v15(),
        algorithm=hashes.SHA256())
    return base64.b64encode(signature).decode()
@app.post("/create_order")
async def create_order(request: Request, data: sheams.CreateOrderRequest):
    openid = data.openId
    product_name = data.productName
    product_num = data.productNum
    product_price = data.productPrice
    url = settings.WECHAT['prepay_id_url']
    timestamp = str(int(time.time()))
    nonce_str = str(uuid.uuid4()).replace('-', '')
    body = {
        "appid": settings.WECHAT['app_id'],
        "mchid": settings.WECHAT['mch_id'],
        "description": f"购买商品：{product_name} x {product_num}",
        "notify_url": settings.WECHAT['notify_url'],
        "out_trade_no": "202409011010100005",
        "amount": {"total": product_price, "currency": "CNY"},
        "payer": {"openid": openid}
    }
    body_json = json.dumps(body)
    # 生成请求签名
    sign_list = [Method.POST.value, settings.WECHAT['sign_url'], timestamp, nonce_str, body_json]
    sign_str = '\n'.join(sign_list) + '\n'
    signature = generate_signature(sign_str)
    headers = {
        "Content-Type": "application/json",
        "Accept": "application/json",
        "Authorization": f'WECHATPAY2-SHA256-RSA2048 mchid="{settings.WECHAT["mch_id"]}",nonce_str="{nonce_str}",signature="{signature}",timestamp="{timestamp}",serial_no="{settings.WECHAT["mch_serial_no"]}"'
    }
    response = requests.post(url, data=body_json, headers=headers)
    print(response.json())
    package = f"prepay_id={response.json().get('prepay_id')}"
    # 生成支付签名
    pay_list = [settings.WECHAT['app_id'], timestamp, nonce_str, package]
    pay_str = '\n'.join(pay_list) + '\n'
    pay_signature = generate_signature(pay_str)
    return {
        'appId': settings.WECHAT['app_id'],
        'package': package,
        'timeStamp': timestamp,
        'nonceStr': nonce_str,
        'signType': 'RSA',
        'paySign': pay_signature
    }